import logging

from django.core.exceptions import PermissionDenied
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, render_to_response
from django.views import View
from django.views.generic.detail import DetailView

from accounts.models import UserProfile
from outlines.serializers import SeceneMarkDescSerializer, JSONResponse
from utils.mixin_utils import LoginRequiredMixin
from .models import Secene, Comment, SeceneDescType, SeceneMarkDesc, Outline

# logger
logger = logging.getLogger(__name__)


# Create your views here.
def ueditor_template(request, secene_id, which_image=1, top=0, left=0):
    desc_type_list = SeceneDescType.objects.all()
    return render_to_response(template_name='secene/_ueditor4mark.html',
                              context={'secene_id': secene_id, 'which_image': which_image, 'top': top, 'left': left,
                                       'desc_type_list': desc_type_list})


class IndexView(View):
    # 在 get_context_data() 函数中可以用于传递一些额外的内容到网页
    def get(self, request, *args, **kwargs):
        # 获取当前用户
        user = self.request.user
        if user.is_authenticated:
            all_outline_list = Outline.objects.all().order_by('sort_order')
            all_secene_list = Secene.objects.all()
        return render(request, 'index.html', locals())


class SeceneDetailView(LoginRequiredMixin, DetailView):
    model = Secene

    template_name = 'secene/detail.html'

    # 在 get_context_data() 函数中可以用于传递一些额外的内容到网页
    def get_context_data(self, **kwargs):
        user = self.request.user
        person_id = self.kwargs.get('person_id', -1)
        type_id = self.kwargs.get('type_id', -1)
        secene_id = kwargs.get('object').id
        context = super(SeceneDetailView, self).get_context_data(**kwargs)
        secene_mark_queryset = SeceneMarkDesc.objects.all().filter(secene_id=secene_id)
        if int(person_id) != -1:
            secene_mark_queryset = secene_mark_queryset.filter(user_id=person_id)
        if int(type_id) != -1:
            secene_mark_queryset = secene_mark_queryset.filter(type_id=type_id)
        context['desc_type_list'] = SeceneDescType.objects.all()
        context['person_list'] = UserProfile.objects.filter(is_active=True, is_staff=False)
        context['secene_mark_list'] = secene_mark_queryset
        context['secene_comment'] = Comment.objects.filter(secene__id=secene_id).order_by('-add_time')
        context['active_person_id'] = int(person_id)
        context['active_type_id'] = int(type_id)
        return context


def secene_mark_list(request, type_id=-1, user_id=-1):
    mark_desc = SeceneMarkDesc.objects.all()
    if type_id is not -1:
        mark_desc = mark_desc.filter(type=type_id)
    if user_id is not -1:
        mark_desc = mark_desc.filter(user=user_id)
    serializer = SeceneMarkDescSerializer(mark_desc, many=True)
    return JSONResponse(serializer.data)


class SeceneMarkView(View):
    """
    添加图片标注
    """

    def post(self, request, *args, **kwargs):
        # 获取当前用户
        user = self.request.user
        # 获取提交的数据
        secene_id = self.request.POST.get("seceneId", None)
        which_image = self.request.POST.get("whichImage", None)
        type_id = self.request.POST.get("typeId", None)
        top = self.request.POST.get("top", None)
        left = self.request.POST.get("left", None)
        content = self.request.POST.get("content", None)
        # 判断当前用户是否是活动的用户
        if not user.is_authenticated():
            logger.error('[SeceneMarkView]当前用户非活动用户:[%s]' % user.username)
            return HttpResponse(u"请登陆！", status=403)
        if not content:
            logger.error('[SeceneMarkView]当前用户输入空标注:[%s]' % user.username)
            return HttpResponse(u"请输入标注内容！", status=403)
        try:
            # 默认使用pk来索引
            secene = Secene.objects.get(pk=secene_id)
        except Secene.DoesNotExist:
            logger.error('[SeceneMarkView]此情景不存在:[%s]' % secene_id)
            raise PermissionDenied
        tooltipbg = "bgblack"
        round_bgw = "roundBgW"
        # 从哪个地方呈现
        animationtype = ('btt-slide', 'rtl-slide', 'ltr-slide')
        theme = ' data-button="moreblue" data-tooltipbg="' + tooltipbg + '" data-round="' + round_bgw + '" data-animationtype="' + \
                animationtype[2] + '"'
        result = '<div class="ip_tooltip ip_img32" style="top: ' + top + 'px; left: ' + left + 'px;"' + theme + ' >' + content + '</div>'
        try:
            # 默认使用pk来索引
            related_type = SeceneDescType.objects.get(pk=type_id)
        except Secene.DoesNotExist:
            logger.error('[SeceneMarkView]此类型不存在:[%s]' % type_id)
            raise PermissionDenied
        # 保存评论
        SeceneMarkDesc.objects.create(
            user=user,
            secene=secene,
            content=result,
            type=related_type,
            image_num=which_image,
        )
        return HttpResponse("success", status=200)


class CommentView(View):
    def post(self, request, *args, **kwargs):
        # 获取当前用户
        user = self.request.user
        # 获取评论
        comment = self.request.POST.get("comment", "")
        # 判断当前用户是否是活动的用户
        if not user.is_authenticated():
            logger.error('[CommentView]当前用户非活动用户:[%s]' % user.username)
            return HttpResponse(u"请登陆！", status=403)
        if not comment:
            logger.error('[CommentView]当前用户输入空评论:[%s]' % user.username)
            return HttpResponse(u"请输入评论内容！", status=403)

        secene_id = self.kwargs.get('secene_id', '')
        try:
            # 默认使用pk来索引(也可根据需要使用title,en_title在索引
            secene = Secene.objects.get(pk=secene_id)
        except Secene.DoesNotExist:
            logger.error('[CommentView]此情景不存在:[%s]' % secene_id)
            raise PermissionDenied

        # 保存评论
        comment = Comment.objects.create(
            user=user,
            secene=secene,
            content=comment,
        )
        mugshot_thumbnail = None
        try:
            mugshot_thumbnail = comment.user.mugshot_thumbnail
        except Exception as e:
            logger.error('[CommentView]用户头像不存在:[%s]' % secene_id)
        # 返回当前评论
        html = "<li class='clearfloat'><div class='comment-tx'>\
        <img src=" + mugshot_thumbnail.url + " style='width:40px;'/></div>\
        <div class='comment-content'><p><a><strong>" + comment.user.username + "</strong></a>\
        <span>" + comment.add_time.strftime("%Y-%m-%d %H:%I:%S") + "</span></p>" + "\
        <p>评论：" + comment.content + "</p></div></li>"

        return HttpResponse(html)
